/*
 * @lc app=leetcode.cn id=712 lang=javascript
 *
 * [712] 两个字符串的最小ASCII删除和
 */

// @lc code=start
/**
 * @param {string} s1
 * @param {string} s2
 * @return {number}
 */
var minimumDeleteSum = function (s1, s2) {
  const m = s1.length;
  const n = s2.length;

  if (m === 0 || n === 0) return Math.abs(m - n);

  // 将 word1 的前 i 个字符转换为 word2 的前 j 个字符所需的最少操作数。
  const minStep = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));

  minStep[0][0] = 0;
  // 从空变为word2的最少操作数
  for (let x = 1; x <= n; x++)
    minStep[0][x] = minStep[0][x - 1] + s2.charCodeAt(x - 1);
  // 从word1变为空的最少操作数
  for (let x = 1; x <= m; x++)
    minStep[x][0] = minStep[x - 1][0] + s1.charCodeAt(x - 1);

  for (let i = 1; i <= m; i++) {
    for (let j = 1; j <= n; j++) {
      if (s1[i - 1] === s2[j - 1]) minStep[i][j] = minStep[i - 1][j - 1];
      else
        minStep[i][j] = Math.min(
          minStep[i][j - 1] + s2.charCodeAt(j - 1),
          minStep[i - 1][j] + s1.charCodeAt(i - 1)
        );
    }
  }
  return minStep[m][n];
};
// @lc code=end
